<template>
  <el-dialog
    v-model="visible"
    title="确认入库"
    width="500px"
    :close-on-click-modal="false"
    :before-close="handleBeforeClose"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      size="default"
    >
      <el-form-item label="责任部门" prop="department" required>
        <el-select
          v-model="formData.department"
          placeholder="请选择责任部门"
          clearable
          filterable
          style="width: 100%"
        >
          <el-option
            v-for="dept in departmentOptions"
            :key="dept.value"
            :label="dept.label"
            :value="dept.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="确认数量">
        <span>{{ cacheKeys.length }} 个缓存项</span>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确认
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { getDepartments } from "../../../servers";

interface Props {
  modelValue: boolean;
  cacheKeys: string[];
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  cacheKeys: () => [],
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "confirm", department: string, cacheKeys: string[]): void;
  (e: "cancel"): void;
}>();

const formRef = ref<FormInstance | null>(null);
const loading = ref(false);

// 部门选项
const departmentOptions = ref<Array<{ label: string; value: string }>>([]);

// 加载部门列表
const loadDepartments = async () => {
  try {
    const result = await getDepartments();
    if (result && typeof result === 'object' && 'departments' in result) {
      departmentOptions.value = result.departments;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取部门列表失败");
  }
};

// 表单数据
const formData = reactive({
  department: "",
});

// 表单验证规则
const formRules: FormRules = {
  department: [
    { required: true, message: "请选择责任部门", trigger: "change" },
  ],
};

// 计算 visible
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit("update:modelValue", value);
  },
});

// 监听弹窗打开，重置表单
watch(visible, (newVal) => {
  if (newVal) {
    formData.department = "";
    formRef.value?.clearValidate();
  }
});

// 初始化加载部门列表
onMounted(() => {
  loadDepartments();
});

// 关闭前回调
const handleBeforeClose = () => {
  visible.value = false;
};

// 取消
const handleCancel = () => {
  visible.value = false;
  emit("cancel");
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    // 表单验证
    await formRef.value.validate();

    if (props.cacheKeys.length === 0) {
      ElMessage.warning("请选择要确认的缓存项");
      return;
    }

    emit("confirm", formData.department.trim(), props.cacheKeys);
    visible.value = false;
  } catch (error: any) {
    // 验证失败不做处理
    return;
  }
};
</script>

<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>

